package com.baizan.daka.util

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.StringRes
import com.baizan.daka.MyApp
import com.baizan.daka.util.AppUtils.Companion.dp2px
import com.dianzan.daka.R

class ToastUtils {
    companion object{
        private var mToast: Toast? = null
        private val mHandler = Handler(Looper.getMainLooper())
        private val r = Runnable {
            if (mToast != null) mToast!!.cancel()
            mToast = null // toast隐藏后，将其置为null
        }


        fun showMShort(message: String?) {
//            try {
//                AnimToastUtil.showShort(message)
//                //            NofToastUtils.showSystemToast(message);
//            } catch (e: Exception) {
//                //采用原始的toast
//                showAndroidToastShort(message)
//            }
            showAndroidToastShort(message)
        }

        fun showShort(@StringRes message: Int) {
            val str: String = MyApp.instance.getResources().getString(message)
            showMShort(str)
        }


        fun showAndroidToastShort(message: String?) {
            mHandler.removeCallbacks(r)
            if (mToast == null) { // 只有mToast==null时才重新创建，否则只需更改提示文字
                val context  = MyApp.instance
                val inflater =
                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                val view: View =
                    inflater.inflate(R.layout.layout_center_toast, null) // 自定义布局
                val text =
                    view.findViewById<View>(R.id.toast_message) as TextView // 显示的提示文字
                text.text = message
                mToast = Toast(context)
                mToast!!.setGravity(Gravity.CENTER, 0, dp2px(-60.0f))
                mToast!!.duration = Toast.LENGTH_SHORT
                mToast!!.view = view
                mToast!!.show()
            } else {
                val text = mToast!!.view.findViewById<TextView>(R.id.toast_message)
                text.text = message
                mToast!!.duration = Toast.LENGTH_SHORT
            }
            mHandler.postDelayed(r, 1000) // 延迟1秒隐藏toast
        }
    }
}